Yes.
try{}
BlocksA method can catch some exceptions and not others. Since problems with closing a file are rare, not catching this one would be tolerable. But a commercial-grade program should take care of everything. Here is one way:
try
{
// other stuff goes here
try
{
while ( true )
sum += instr.readInt();
}
catch ( EOFException eof )
{
System.out.println( "The sum is: " + sum );
instr.close();
}
catch ( IOException iox )
{
System.out.println( "Problems reading " + fileName );
instr.close();
}
}
catch ( IOException iox )
{
System.out.println( "IO Problems with" + fileName );
}
The logic dealing with reading input and catching end of file
is put inside a try{}
block that is concerned with
errors.
This is messy,
but IO programming always is.
This example is probably
more complicated than you would
normally write.
It can be slightly simplified by using a finally{}
block inside the nested try{}
block.
If the readInt()
throws an IOException
,
where will it be caught?